﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Yz.Core.Extensions
{
    public static class DesEncryptExtension
    {
        //默认密钥向量 
        private const string encryptKey = "Yz";



        #region Des加密解密

        /// <summary>
        ///     加密数据
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string ToDesEncrypt(this string value, string sKey = encryptKey)
        {
            var des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(value);
            string md5Key = sKey.ToMd5Hash().Substring(0, 8);
            des.Key = Encoding.ASCII.GetBytes(md5Key);
            des.IV = Encoding.ASCII.GetBytes(md5Key);
            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            var ret = new StringBuilder();
            foreach (var b in ms.ToArray()) ret.AppendFormat("{0:X2}", b);
            return ret.ToString();
        }

        /// <summary>
        ///     解密数据
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string ToDesDecrypt(this string value, string sKey = encryptKey)
        {
            var des = new DESCryptoServiceProvider();
            int len;
            len = value.Length / 2;
            var inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(value.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            string md5Key = sKey.ToMd5Hash().Substring(0, 8);
            des.Key = Encoding.ASCII.GetBytes(md5Key);
            des.IV = Encoding.ASCII.GetBytes(md5Key);
            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }


        #endregion

        #region 3Des加密解密
        /// <summary>
        /// 3Des解密
        /// </summary>
        /// <param name="value"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string ToDes3Decrypt(this string value, string key = encryptKey)
        {
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider
            {
                Key = ASCIIEncoding.ASCII.GetBytes(key),
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7
            };

            ICryptoTransform DESDecrypt = des.CreateDecryptor();
            byte[] Buffer = Convert.FromBase64String(value);
            string result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
            return result;
        }
        /// <summary>
        /// 3Des加密
        /// </summary>
        /// <param name="value"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string ToDes3Encrypt(this string value, string key = encryptKey)
        {
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider
            {
                Key = ASCIIEncoding.ASCII.GetBytes(key),
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7
            };

            ICryptoTransform DESEncrypt = des.CreateEncryptor();

            byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(value);
            return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
        }
        #endregion 

        #region AES加密解密
        /// <summary>
        ///  AES 加密
        /// </summary>
        /// <param name="value">明文（待加密）</param>
        /// <param name="key">密文</param>
        /// <returns></returns>
        public static string ToAesEncrypt(this string value, string key = encryptKey)
        {
            if (string.IsNullOrEmpty(value)) return null;
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(value);

            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="value">明文（待解密）</param>
        /// <param name="key">密文</param>
        /// <returns></returns>
        public static string ToAesDecrypt(this string value, string key = encryptKey)
        {
            if (string.IsNullOrEmpty(value)) return null;
            Byte[] toEncryptArray = Convert.FromBase64String(value);

            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Encoding.UTF8.GetString(resultArray);
        }
        #endregion AES加密解密

    }
}
